#include "QLibSsh/sshchannel.h"

SshChannel::SshChannel(const ssh_channel& channel)
    : SharePtr(channel)
{
}

SshChannel::~SshChannel()
{
    if (mPtr == nullptr) {
        return;
    }

    mRefCount->fetch_sub(1, std::memory_order_relaxed);
    if (mRefCount->load(std::memory_order_relaxed) == 0) {
        if (ssh_channel_is_eof(mPtr)) {
            ssh_channel_send_eof(mPtr);
        }
        if (ssh_channel_is_open(mPtr)) {
            ssh_channel_close(mPtr);
        }
        ssh_channel_send_eof(mPtr);
        ssh_channel_free(mPtr);
    }

    mPtr = nullptr;
    mRefCount = nullptr;
}


bool SshChannel::RunInteractiveShell() const {
    if (IsNull() || !IsOpen()) {
        qDebug() << "IsNull() || !IsOpen()";
        return false;
    }

    if (ssh_channel_request_pty(mPtr) != SSH_OK) {
        qDebug() << "ssh_channel_request_pty(mSshChannel) != SSH_OK";
        return false;
    }

    if (ssh_channel_request_shell(mPtr) != SSH_OK) {
        qDebug() << "ssh_channel_request_shell(mSshChannel) != SSH_OK";
        return false;
    }

    return true;
}

bool SshChannel::ChangeShellSize(int cols, int rows) const {
    if (IsNull() || !IsOpen()) {
        return false;
    }

    if (ssh_channel_change_pty_size(mPtr, cols, rows) != SSH_OK) {
        return false;
    }
    return true;
}
